# -*- coding: UTF-8 -*-
# 2023/11/30 20:49
import os.path
from threading import Thread

import requests
from ttkbootstrap import Checkbutton, BooleanVar
from ttkbootstrap.scrolled import ScrolledFrame

from phone.double_clicked_top import double_clicked_top
from phone.pool_download_preview_img import pool_download_preview_img
from tools.get_configer import my_configer
from tools.get_logger import get_logger

configer = my_configer()
loger = get_logger()


class class_hot_new_search_frame(ScrolledFrame):
    def __init__(self, line_num, name_id_tag_urls, **kwargs):
        """
        {
            "img_name": f'{"_".join(img_info["tag"])}_{img_info["id"]}.jpg',
            "img_id": img_info["id"],
            "img_tag": "-".join(img_info["tag"]),
            "img_urls":
                {
                    "thumb": img_info["thumb"],  # 预览350*540
                    "img": img_info["img"],  # 标准大小1080*1920
                    "preview": img_info["preview"]  # 最大2000*300,存在损坏的
                }
        }
        """
        super().__init__(**kwargs)

        self.master = kwargs["master"]
        self.line_num = line_num
        self.name_id_tag_urls = name_id_tag_urls

        self.page_btn_list = list()  # 生成的所有按钮
        self.btn_variable_list = list()

        self.add_img_class()

    def add_img_class(self):
        """
        以按钮图片形式添加图片到ScrolledFrame中
        """
        row = 0
        for column in range(len(self.name_id_tag_urls)):
            img_name_id_urls = self.name_id_tag_urls[column]

            # 创建组件并给组件添加img_id、img_url、save_path属性方便后面异步使用
            btn_variable = BooleanVar()
            check_btn = Checkbutton(self, variable=btn_variable)

            # 绑定属性方便线程池调用
            setattr(check_btn, "variable", btn_variable)
            setattr(check_btn, "img_name_id_urls", img_name_id_urls)

            setattr(btn_variable, "img_name_id_urls", img_name_id_urls)

            # 设置双击预览
            check_btn.bind("<Double-Button-1>", self.double_clicked)

            # 布局和拉伸策略
            if column % self.line_num == 0 and column != 0:
                row += 1
            check_btn.grid(row=row, column=column % self.line_num, ipadx=10, ipady=10)
            self.master.grid_rowconfigure(row, weight=1)
            self.master.grid_columnconfigure(column % self.line_num, weight=1)

            loger.info(f"批量生成多选按钮预览,按钮绑定信息:{img_name_id_urls}")

            # 把生成的按钮和按钮状态加入按钮列表
            self.page_btn_list.append(check_btn)
            self.btn_variable_list.append(btn_variable)

        thread_pool_download_thred = Thread(target=pool_download_preview_img, args=(self.page_btn_list,), daemon=True)
        thread_pool_download_thred.start()

    def double_clicked(self, event):
        """
        预览按钮双击回调
        """
        button = event.widget
        img_name_id_urls = getattr(button, "img_name_id_urls")
        img_url = img_name_id_urls["img_urls"]["img"][0]  # 这里解析出来是元组
        img_name = img_name_id_urls["img_name"]
        save_path = os.path.abspath(f"./cache/phone_cache/max_{img_name}")

        loger.info(f"触发了双击预览图像, 图像保存位置:{save_path},图片url:{img_url}")
        self.download_img(img_url, save_path)

        double_clicked_top(save_path,
                           title=img_name,  # 窗口标题
                           resizable=(False, False)  # 拉伸策略
                           )

    def download_img(self, url: str, save_path: str) -> None:
        """
        根据传入的图片地址,进行下载
        :param self:
        :param url: 图片url
        :param save_path: 保存路径
        :return:
        """

        r = requests.get(url)
        response = r.content

        with open(save_path, "wb") as f:
            f.write(response)

        r.close()

        loger.info(f"预览图片保存成功,保存位置:{save_path},图片url:{url}")

    def get_select_btn(self):
        """
        获取当前所有已勾选的按钮列表
        """
        download_info_list = list()
        for btn_variable in self.btn_variable_list:
            name_id_tag_urls_dict = getattr(btn_variable, "img_name_id_urls")
            button_select_state = btn_variable.get()

            if button_select_state:
                download_info_list.append(name_id_tag_urls_dict)
                loger.info(f"检查到选择,加入下载队列图片信息,name:{name_id_tag_urls_dict['img_name']}, all_info:{name_id_tag_urls_dict}")

        return download_info_list

    def get_all_btn(self):
        """
        获取当前所有已勾选的按钮列表
        """

        download_info_list = list()
        for btn_variable in self.btn_variable_list:
            name_id_tag_urls_dict = getattr(btn_variable, "img_name_id_urls")
            name_id_tag_urls_dit = getattr(btn_variable, "img_name_id_urls")

            download_info_list.append(name_id_tag_urls_dit)
            loger.info(f"加入下载队列图片信息,name:{name_id_tag_urls_dict['img_name']}, all_info:{name_id_tag_urls_dict}")

        return download_info_list
